<?php

declare(strict_types=1);

namespace App\Controller\MchApi;
use App\Exception\XZXValidationException;
use App\Service\TradeTransService;
use App\Middleware\MchApi\MchJWTAuthMiddleware;
use App\Utils\CustomUtils;
use App\Utils\DateUtils;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Validation\Contract\ValidatorFactoryInterface;
use Hyperf\Contract\TranslatorInterface;

/**
 * Class TradeTransController
 * @package App\Controller
 *
 * @Controller(prefix="/mch/api/tradeTrans")
 */
class TradeTransController extends MchBaseController
{

    /**
     * @Inject
     * @var TranslatorInterface
     */
    private $translator;

    /**
     * @Inject()
     * @var ValidatorFactoryInterface
     */
    protected $validationFactory;

    /**
     * @Inject()
     * @var TradeTransService
     */
    protected $TradeTranService;

    /**
     * @var \Psr\Log\LoggerInterface
     */
    protected $logger;

    public function __construct(LoggerFactory $loggerFactory)
    {
        // 第一个参数对应日志的 name, 第二个参数对应 config/autoload/logger.php 内的 key
        $this->logger = $loggerFactory->get('log', 'default');
    }

    private function setLocale () {
        if ($this->request->header('locale') == 'en') {
            $this->translator->setLocale('en');
        }
    } 

    /**
     * 查看
     * @PostMapping(path = "get")
     * @Middleware(MchJWTAuthMiddleware::class)
     */
    public function get(RequestInterface $request)
    {
        $this->setlocale();
        $validator = $this->validationFactory->make(
            $request->all(),
            [
                'id' => 'required',
            ]
        );

        if ($validator->fails()){
            // Handle exception
            $errorMessage = $validator->errors()->first();  
            throw new XZXValidationException($errorMessage);
        }

        $param = $request->all();
        return $this->TradeTranService->get($param);
    }

    /**
     * 添加
     * @PostMapping(path = "add")
     * @Middleware(MchJWTAuthMiddleware::class)
     */
    public function add(RequestInterface $request)
    {
        $this->setlocale();
        $validator = $this->validationFactory->make(
            $request->all(),
            [
                'code'              => 'required',
                'type'              => 'required',
                'transAmount'       => 'required',
                'targetCurrency'    => 'required',
            ]
        );

        if ($validator->fails()){
            // Handle exception
            $errorMessage = $validator->errors()->first();  
            throw new XZXValidationException($errorMessage);
        }
        $param = $request->all();
        // 转账的还要判断
        if ($param['type'] == 2 && empty($param['extraType'])) {
            throw new XZXValidationException("extraType 不能为空");
        }
        if ($param['type'] == 2 && $param['extraType'] == 2 &&
            (!isset($param['targetMchEmail']) || empty($param['targetMchEmail']))) {
            throw new XZXValidationException("转账收款方邮箱 不能为空");
        }
        if ($param['type'] == 2 && $param['extraType'] == 1 &&
            (!isset($param['bankAccountName']) || !isset($param['bankAccountNo']) || !isset($param['bankOpenBankNo']) ||
            empty($param['bankAccountName']) || empty($param['bankAccountNo']) || empty($param['bankOpenBankNo']))) {
            throw new XZXValidationException("转账银行信息 不能为空");
        }

        $ext = $this->request->getAttribute("ext");
        $param['createBy'] =  $ext['createBy'];
        $param['uid'] =  $ext['uid'];
        $param['mchId'] =  $ext['mchId'];
        // $param['mchNo'] =  $ext['mchNo'];
        return $this->TradeTranService->add($param);
    }

    /**
     * 查询
     * @PostMapping(path = "list")
     * @Middleware(MchJWTAuthMiddleware::class)
     */
    public function list(RequestInterface $request)
    {
        $this->setlocale();
        $validator = $this->validationFactory->make(
            $request->all(),
            [
                'page' => 'required|integer|min:1',
                'limit' => 'required|integer|min:1',
            ]
        );

        if ($validator->fails()){
            // Handle exception
            $errorMessage = $validator->errors()->first();  
            throw new XZXValidationException($errorMessage);
        }
        
        $param = $request->all();

        CustomUtils::xzxDebug($param);
        if(isset($param['search'])){
            $search = $param['search'];
            CustomUtils::xzxAddSearch($param, $search, 'type');
            CustomUtils::xzxAddSearch($param, $search, 'handleStatus');
            if(isset($param["createTimeRange"]))
            {
                try {
                    $param['createTimeRange'][0] = DateUtils::dateToTimeStamp($param['createTimeRange'][0]);
                    $param['createTimeRange'][1] = DateUtils::dateToTimeStamp($param['createTimeRange'][1]);
                } catch (\Throwable $th) {
                    unset($param['createTimeRange']);
                }
            }
        }
        $ext = $this->request->getAttribute("ext");
        $param['mchId'] =  $ext['mchId'];
        
        return $this->TradeTranService->list($param);
    }
   
}